<%--
  Created by IntelliJ IDEA.
  Time: 14:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<html>
<head>
    <title>用户管理</title>
    <link rel="stylesheet" href="../static/layui/css/layui.css" media="all">
</head>
<body>
<div class="layui-row" id="editUser" style="display:none;">
    <div class="layui-col-md10">
        <form class="layui-form layui-from-pane" id="editForm" action="" style="margin-top:20px">
            <div class="layui-form-item">
                <label class="layui-form-label">账号</label>
                <div class="layui-input-block">
                    <input type="text" name="editName" id="editUsername" required lay-verify="required"
                           autocomplete="off"
                           placeholder="请输入用户名" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">密码</label>
                <div class="layui-input-block">
                    <input type="text" name="editName" id="editPassword" required lay-verify="required"
                           autocomplete="off"
                           placeholder="请输入密码" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="editName" id="editName" required lay-verify="required" autocomplete="off"
                           placeholder="请输入姓名" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">性别</label>
                <div class="layui-input-block">
                    <input type="radio" name="editSex" value="1" title="男">
                    <input type="radio" name="editSex" value="2" title="女">
                </div>
            </div>


            <div class="layui-form-item">
                <label class="layui-form-label">学院名</label>
                <div class="layui-input-block">
                    <select name="departmentId" lay-verify="required" id="editDepartmentId">
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">角色</label>
                <div class="layui-input-block">
                    <select name="roleId" lay-verify="required" id="editRoleId">
                    </select>
                </div>
            </div>
        </form>
    </div>
</div>
<table class="layui-hide" id="userList" lay-filter="userList"></table>
<script type="text/html" id="barArticle">
    <shiro:hasPermission name="user:update">
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">
            <i class="layui-icon layui-icon-edit"></i>编辑
        </a>
    </shiro:hasPermission>

    <shiro:hasPermission name="user:del">
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
    </shiro:hasPermission>
</script>

</body>
</html>
<script src="../static/layui/layui.js"></script>
<script>
    let _form;
    let index;
    layui.use(['laydate', 'laypage', 'layer', 'table', 'form', 'element', 'jquery'], function () {
        var laydate = layui.laydate //日期
            , laypage = layui.laypage //分页
            , layer = layui.layer //弹层
            , table = layui.table //表格
            , form = layui.form    //表单
            , element = layui.element //元素操作
            , $ = layui.jquery //jquery

        _form = form;
        index = layer.index;
        //监听Tab切换
        element
            .on('tab(article)', function (data) {
                layer.tips('切换了 ' + data.index + '：' + this.innerHTML, this, {
                    tips: 1
                });
            });

        //执行一个 table 实例
        table.render({
            elem: '#userList'
            , height: 'full-30'
            , url: '/user/findAll' //数据接口
            , title: '用户表'
            , limits: [20, 30, 50, 100]
            , limit: 20
            , page: true //开启分页
            , toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
            , cols: [[
                {type: 'checkbox', fixed: 'left'}//表头
                , {field: 'id', title: 'ID', width: 120, sort: true, fixed: 'left', align: 'center'}
                , {field: 'username', title: '账号名称', width: 200, align: 'center'}
                , {field: 'name', title: '员工名称', width: 200, align: 'center'}
                , {
                    field: 'sex', align: 'center', width: 50, templet: function (d) {
                        if (d.sex === 1) {
                            return '男'
                        } else if (d.sex === 2) {
                            return '女'
                        }
                    }
                }
                , {field: 'departmentName', title: '学院', width: 200, align: 'center'}
                , {field: 'roleName', title: '角色', width: 200, align: 'center'}
                , {fixed: 'right', title: '操作', width: 265, align: 'center', toolbar: '#barArticle'}
            ]]
        });

        //监听头工具栏事件
        table.on('toolbar(userList)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id)
                , data = checkStatus.data; //获取选中的数据
            switch (obj.event) {
                case 'update':

                    break;
                case 'delete':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else {
                        layer.msg('删除');
                    }
                    break;
                case 'add': {  //添加yonghu
                    layer.open({
                        //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                        type: 1,
                        title: "添加用户信息",
                        content: $("#editUser")//引用的弹出层的页面层的方式加载修改界面表单
                        , btn: ['确定', '取消'],
                        success: function (layero, index) {
                            getAllDepartment(index);
                            getAllRoles(index);

                        },

                        btn1: function (index, layero) {
                            $.ajax({
                                url: '/user/add',
                                type: "post",
                                dataType: "json",
                                data: {
                                    username: $("#editUsername").val(),     //账号
                                    password: $("#editPassword").val(),     //密码
                                    name: $("#editName").val(),    //姓名
                                    sex: $("input[name='editSex']:checked").val(),     //性别
                                    departmentId: $("#editDepartmentId").val(),     //学院id
                                    roleId: $("#editRoleId").val()     //角色id
                                },
                                success: function (res) {
                                    if (res.code === 200) {
                                        layer.close(index);
                                        console.log(index);
                                        layer.msg("添加成功", {
                                            icon: 1
                                        }, function () {
                                            window.location.reload();
                                        });
                                    } else {
                                        layer.close(index);
                                        layer.msg("添加失败", {
                                            icon: 5
                                        });
                                    }
                                }
                            });
                        },
                        btn2: function (index, layero) {
                        }
                        , end: function () {
                            resetEditForm();
                        }
                    });
                }
                    break;
            }
            ;
        });

        //监听行工具事件
        table.on('tool(userList)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                , layEvent = obj.event; //获得 lay-event 对应的值
            if (layEvent === 'edit') {
                layer.open({
                    //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                    type: 1,
                    title: "编辑用户信息",
                    content: $("#editUser")//引用的弹出层的页面层的方式加载修改界面表单
                    , btn: ['确定', '取消'],
                    success: function (layero, index) {
                        $("#editUsername").val(data.username);
                        $("#editName").val(data.name);
                        $("input[name='editSex'][value='" + data.sex + "']").attr("checked", true);

                        getAllDepartment(data.departmentName);
                        getAllRoles(data.roleName);
                        form.render();
                    },

                    btn1: function (index, layero) {
                        $.ajax({
                            url: '/user/update',
                            type: "post",
                            dataType: "json",
                            data: {
                                id: obj.data.id,
                                username: $("#editUsername").val(),     //账号
                                password: $("#editPassword").val(),     //密码
                                name: $("#editName").val(),    //姓名
                                sex: $("input[name='editSex']:checked").val(),     //性别
                                departmentId: $("#editDepartmentId").val(),     //学院id
                                roleId: $("#editRoleId").val()     //角色id
                            },
                            success: function (res) {
                                if (res.code === 200) {
                                    layer.close(index);
                                    console.log(index);
                                    layer.msg("更新成功", {
                                        icon: 1
                                    }, function () {
                                        window.location.reload();
                                    });
                                } else {
                                    layer.close(index);
                                    layer.msg("更新失败", {
                                        icon: 5
                                    });
                                }
                            }
                        });
                    },
                    btn2: function (index, layero) {
                    }
                    , end: function () {
                        resetEditForm();
                    }
                });
            } else if (layEvent === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    layer.close(index);
                    //向服务端发送删除指令
                    deleteUser(obj.data.id);
                    obj.del(); //删除对应行（tr）的DOM结构
                    table.reload();
                });
            } else if (layEvent === 'edit') {

            }
        });
        $(document).on('click', '[data-id]', function (e) {
            var me = $(this);
            layer.msg(me.attr("data-id") + '-----' + me.attr("data-state"))
        });

        function deleteUser(id) {
            $.getJSON("/user/del?id=" + id, function (res) {
                if (res.code === 200) {
                    layer.close(index);
                    console.log(index);
                    layer.msg("删除成功", {
                        icon: 1
                    }, function () {
                        window.location.reload();
                    });
                } else {
                    layer.close(index);
                    layer.msg("删除失败", {
                        icon: 5
                    });
                }
            });
        }

        function getAllRoles(roleName) {
            $.getJSON("/role/findAll", function (data) {
                var optionstring = "";
                $.each(data.data, function (i, item) {
                    if (roleName===item.name){
                        optionstring += "<option value=" + item.id + " selected>" + item.name + "</option>";
                    }else {
                        optionstring += "<option value=" + item.id + " > " + item.name + "</option>";
                    }

                });
                $("#editRoleId").html(optionstring);
                _form.render('select'); //这个很重要
            });
        }

        function getAllDepartment(departmentName) {
            $.getJSON("/department/findAll", function (data) {
                var optionstring = "";
                $.each(data.data, function (i, item) {
                    if (departmentName === item.name) {
                        optionstring += "<option value=" + item.id + " selected >" + item.name + "</option>";
                    } else {
                        optionstring += "<option value=" + item.id + " > " + item.name + "</option>";
                    }

                });
                $("#editDepartmentId").html(optionstring);
                _form.render('select'); //这个很重要
            });
        }

        function resetEditForm() {
            $("#editName").val('');
            $("#editUsername").val('');
            $("#editPassword").val('');
            $("select").empty();
            $("#editUser").attr("style", "display:none;");
        }

    });
</script>
